package xyz.syyrjx.filter;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import xyz.syyrjx.annotions.RestrictCalls;
import xyz.syyrjx.entity.ResultInfo;
import xyz.syyrjx.service.RedisRemoteService;
import xyz.syyrjx.utils.RedisUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Mr.Wan
 * @date 2022/10/12 - 21:23
 */
public class RestrictFilter extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = getIp(request);
        if (!RedisUtil.isInBlack(ip)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            RestrictCalls restrictCallsAnnotion = handlerMethod.getMethodAnnotation(RestrictCalls.class);
            if (null != restrictCallsAnnotion) {
                return addRequsetCount(ip, restrictCallsAnnotion);
            }
            return true;
        }
        //打日志
        System.out.println(ip + "在黑名单中");
        //抛异常也拦截
        return false;
    }


    /**
     * 添加访问记录
     *
     * @param ip                    ip地址
     * @param restrictCallsAnnotion 限制注解
     * @return 是否被加入黑名单
     */
    public boolean addRequsetCount(String ip, RestrictCalls restrictCallsAnnotion) {
        long max = restrictCallsAnnotion.count();
        long count = RedisUtil.blackCount(ip);
        if (max == count){
            RedisUtil.blackAdd(ip);
            return false;
        }
        return true;

    }


    /**
     * 获取ip
     *
     * @param request 请求对象
     * @return 返回ip地址
     */
    private String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (null == ip || 0 == ip.length() || "unknown".equals(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (null == ip || 0 == ip.length() || "unknown".equals(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (null == ip || 0 == ip.length() || "unknown".equals(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
